'use strict';

import gulp  from 'gulp';
import Promise from 'promise';
import fs from 'fs';
import pkg from './package.json';
import _$ from 'gulp-load-plugins';

const $ = _$();

const base = 'src', build = 'build', jsDir = 'javascript';
const dist = 'dist', _public = build + '/public';
const projectName = 'validator';
const allFileName = projectName.replace(/-/g, '.') + '.min.js';

gulp.task('copy:html', () => {
    return gulp.src(base + '/html/*.html')
        .pipe(gulp.dest(_public + '/'));
});

gulp.task('copy:libs', () => {
    return gulp.src(base + '/libs/**')
        .pipe(gulp.dest(_public + '/' + jsDir + '/libs/'));
});

gulp.task('copy', gulp.parallel('copy:html', (done) => done()));

gulp.task('clean', () => {
    return gulp.src([build + '/*', dist + '/*'],
        {read: false})
        .pipe($.clean());
});

gulp.task('scripts', gulp.parallel('copy:libs', () => {
    const jsDist = _public + '/' + jsDir,
        jsSrc = base + '/' + jsDir;
    const source = jsSrc.concat('/**/*.js');
    return gulp.src(source, {base: jsSrc})
        .pipe($.jshint('.jshintrc'))
        .pipe($.jshint.reporter('default'))
        .pipe($.babel({
            presets: [['env', {
                "targets": {
                    "browsers": ["last 2 versions", "ie 6-8"]
                }
            }]]
        }))
        .pipe(gulp.dest(jsDist))
        .pipe($.rename({suffix: '.min'}))
        .pipe($.uglify())
        .pipe(gulp.dest(jsDist));
}));

gulp.task('build', gulp.series('clean', 'copy', 'scripts', (done) => {
    done();
}));

gulp.task('live', gulp.series('build', () => {
    // js
    gulp.watch(base + '/' + jsDir + '/**.js', gulp.parallel('scripts'));
    // html
    gulp.watch(base + '/html' + '/*.html', gulp.parallel('copy:html'));
}));

gulp.task('copy:dist', gulp.series('build', () => {
    return gulp.src(_public + '/**/*.js', {base: _public + '/javascript/'})
        .pipe(gulp.dest(dist))
}));

gulp.task('dist:concat', gulp.series('copy:dist', () => {
    return gulp.src([dist + '/*.min.js'], {base: dist})
        .pipe($.concat(allFileName))
        .pipe(gulp.dest(dist));
}));

gulp.task('dist:header', gulp.series('dist:concat', () => {
    const p = dist;
    const r = (path) => {
        return p + '/' + path;
    };
    return Promise.all([
        new Promise((resolve) => {
            gulp.src([r('/*.min.js')], {base: dist})
                .pipe($.header(fs.readFileSync('header.txt', 'utf8'), {pkg: pkg}))
                .pipe(gulp.dest(dist, {overwrite: true}))
                .on('finish', () => resolve());
        })
    ]);
}));

gulp.task('dist', gulp.series('dist:header', (done) => done()));

gulp.task('default', gulp.series('clean', 'build', (done) => done()));
